package com.zy.je.common.core.utils.crypto;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;


/**
 * @author zy
 */
public class DesUtil {

    public static String encrypt(String source, String keyData) {
        byte[] ret = encrypt(source.getBytes(StandardCharsets.UTF_8), keyData);
        return new String(Base64.getEncoder().encode(ret), StandardCharsets.UTF_8);
    }

    public static String decrypt(String encryptedData, String keyData) {
        byte[] ret = descrypt(Base64.getDecoder().decode(encryptedData.getBytes(StandardCharsets.UTF_8)), keyData);
        return new String(ret, StandardCharsets.UTF_8);
    }

    private static Cipher buildCipher(String keyData, int encryptMode /*Cipher.ENCRYPT_MODE/ Cipher.DECRYPT_MODE*/) throws Exception {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(keyData.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);

        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(encryptMode, key, sr);
        return cipher;
    }

    private static byte[] encrypt(byte[] primaryData, String keyData) {
        try {
            Cipher cipher = buildCipher(keyData, Cipher.ENCRYPT_MODE);
            byte encryptedData[] = cipher.doFinal(primaryData);
            return encryptedData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static byte[] descrypt(byte[] encryptedData, String keyData) {
        try {
            Cipher cipher = buildCipher(keyData, Cipher.DECRYPT_MODE);
            byte decryptedData[] = cipher.doFinal(encryptedData);
            return decryptedData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 生成密钥
     * @return
     */
    public static String generateKey() {
        try {
            SecureRandom sr = new SecureRandom();
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(sr);
            SecretKey key = kg.generateKey();
            byte rawKeyData[] = key.getEncoded();
            return Base64.getEncoder().encodeToString(rawKeyData);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}